package com.jader.activities;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jader.adapter.SpinnerAdapter;
import com.jader.main.MainActivity;
import com.jader.myviews.MyProgressDialog;
import com.jader.util.Config;
import com.jader.util.JaderApplication;
import com.jader.util.PreferenceUtil;
import com.jader.util.StringUtils;
import com.jader.util.Textnum;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class FActivity extends Activity implements OnClickListener {
	private Dialog dialog;// 获取图片的弹出框
	File file;// 文件
	LinearLayout ll_imgs;// 图片布局
	List<String> imgs_path;// 上传图片的路径
	ImageView addGoodsPic;// 添加图片
	int index = -1;// 记录要替换的图片 当为-1时 为新增
	String tempImgName;// 图片名
	Button quxiaofabu, qurenfabu;

	EditText tittleEditText, contenteEditText;// 定义一个文本输入框
	Spinner spinner;// 动态选择
	TextView textView;// 用来显示剩余字数
	int num = 1000;// 最大字数限制
	Intent intent;
	String t_tittle, t_content;// 标题、内容
	int user_id;//发帖者ID
	String tieziId;// 帖子ID
	String date;// 日期
	int dongtaifenlei;// 动态分类
	// boolean t_hidden;
	String pl_path;
	MyProgressDialog dialog2;
	private SpinnerAdapter spinnerAdapter;
	// String[] arrays = { "所有", "估价", "定制", "话题" };
	String[] arrays = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.fabu_dongtai);
		arrays = getResources().getStringArray(R.array.plantes);
		spinnerAdapter = new SpinnerAdapter(this, arrays);
		initData();
		initViews();

	}

	private void initData() {
		imgs_path = new ArrayList<String>();// 初始化图片路径 定义成一个集合

	}

	@SuppressLint("SimpleDateFormat")
	private void Tools() {
		t_tittle = tittleEditText.getText().toString();
		t_content = contenteEditText.getText().toString();
		// 日期
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date time = new Date(System.currentTimeMillis());
		date = format.format(time);
		// 帖子ID
		SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmsssss");
		Date time1 = new Date(System.currentTimeMillis());
		tieziId = format1.format(time1);
	}

	private void initViews() {
		dialog2=JaderApplication.getMyDialog(this);
		ll_imgs = (LinearLayout) findViewById(R.id.fabu_tupian);
		addGoodsPic = (ImageView) findViewById(R.id.fabu_tupiantianjia);
		addGoodsPic.setOnClickListener(this);

		spinner = (Spinner) findViewById(R.id.spinner);
		spinner.setAdapter(spinnerAdapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				dongtaifenlei = arg2;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		// 对标题栏和内容栏进行初始化
		tittleEditText = (EditText) findViewById(R.id.fabu_biaoti);
		contenteEditText = (EditText) findViewById(R.id.fabu_write_neirong);

		textView = (TextView) findViewById(R.id.fabu_neirongzishu);
		Textnum.numtext(contenteEditText, textView, num);
		quxiaofabu = (Button) findViewById(R.id.quxiaofabu);
		qurenfabu = (Button) findViewById(R.id.querenfabu);
		quxiaofabu.setOnClickListener(this);
		qurenfabu.setOnClickListener(this);

	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.quxiaofabu:
			Intent intent = new Intent(FActivity.this, MainActivity.class);
			intent.putExtra("tiaozhuan", 1);
			startActivity(intent);
			break;
		case R.id.fabu_tupiantianjia:// 点击添加图片
			index = -1;
			showPhotoDialog();
			break;
		case R.id.paizhao:// 打开相机
			openCamera();
			break;
		case R.id.xiangce:// 打开图库
			openPhones();
			break;
		case R.id.quxiao:// 取消
			dialog.cancel();
			break;
		case R.id.querenfabu:
			// 信息完整性验证后调用提交
			if (checkParameter()) {
				uploadGoods();

				
			}
			break;
		default:
			break;
		}
	}

	private void openCamera() {
		dialog.dismiss();
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		tempImgName = StringUtils.getImageSaveName();
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
				FActivity.this.getExternalCacheDir(), tempImgName)));
		Log.e("error", tempImgName);
		startActivityForResult(intent, Config.REQUEST_CODE_CAMERA);
	}

	private void openPhones() {
		dialog.dismiss();
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		startActivityForResult(intent, Config.REQUEST_CODE_OPENPICS);
	}

	void addImageView(Uri uri) {
		String img_path = getExternalCacheDir() + File.separator + tempImgName;
		Log.e("error_188", img_path);
		if (index == -1) {
			final ImageView imageView = new ImageView(this);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					addGoodsPic.getWidth(), addGoodsPic.getHeight());
			params.setMargins(20, 0, 0, 0);
			imageView.setLayoutParams(params);
			imageView.setImageURI(uri);
			final int n = imgs_path.size();// 当前商品图片数量
			imageView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(final View v) {
					new AlertDialog.Builder(FActivity.this)
							.setNegativeButton(R.string.cancle,
									new DialogInterface.OnClickListener() {

										// 取消
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									})
							.setNeutralButton(
									getResources().getString(R.string.edit),
									new DialogInterface.OnClickListener() {
										// 编辑
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											dialog.dismiss();
											showPhotoDialog();
											index = ll_imgs.indexOfChild(v);

										}
									})
							.setPositiveButton(R.string.delete,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// 删除
											dialog.dismiss();
											removeImageView(v);
										}
									}).show();

				}
			});
			ll_imgs.addView(imageView, n);
			// 添加图片路径
			imgs_path.add(img_path);
			Log.e("error_245", img_path.toString());

		} else {
			ImageView imageView = (ImageView) ll_imgs.getChildAt(index);
			imageView.setImageURI(uri);
			imgs_path.set(index, img_path);
		}

	}

	void removeImageView(View v) {
		imgs_path.remove(ll_imgs.indexOfChild(v));
		StringUtils.showToast(FActivity.this, "" + ll_imgs.indexOfChild(v));
		ll_imgs.removeView(v);
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		tempImgName = StringUtils.getImageSaveName();
		intent.putExtra("output",
				Uri.fromFile(new File(this.getExternalCacheDir(), tempImgName)));
		startActivityForResult(intent, Config.REQUEST_CODE_ZOOM);
	}

	private void showPhotoDialog() {
		View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog,
				null);
		view.findViewById(R.id.paizhao).setOnClickListener(this);
		view.findViewById(R.id.xiangce).setOnClickListener(this);
		view.findViewById(R.id.quxiao).setOnClickListener(this);
		dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
		dialog.setContentView(view, new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT));
		Window window = dialog.getWindow();
		// 设置显示动画
		window.setWindowAnimations(R.style.main_menu_animstyle);
		WindowManager.LayoutParams wl = window.getAttributes();
		wl.x = 0;
		wl.y = getWindowManager().getDefaultDisplay().getHeight();
		// 以下这两句是为了保证按钮可以水平满屏
		wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
		wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
		// 设置显示位置
		dialog.onWindowAttributesChanged(wl);
		// 设置点击外围解散
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("error", requestCode + "-->" + resultCode);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case Config.REQUEST_CODE_CAMERA:
				File file = new File(this.getExternalCacheDir(), tempImgName);
				startPhotoZoom(Uri.fromFile(file));
				break;
			case Config.REQUEST_CODE_OPENPICS:
				Uri uri = data.getData();
				startPhotoZoom(uri);
				break;

			case Config.REQUEST_CODE_ZOOM:
				File file2 = new File(getExternalCacheDir(), tempImgName);
				addImageView(Uri.fromFile(file2));
				break;

			default:
				break;
			}
		}
	}

	boolean checkParameter() {
		// 没有选择商品图片的
		if (tittleEditText.getText().length() == 0) {
			StringUtils.showToast(this, Config.ERROR_NO_TITLE);
			tittleEditText.requestFocus();
			return false;
		} else if (tittleEditText.getText().length() < 1) {
			StringUtils.showToast(this, Config.ERROR_TITLE_TOSHORT);
			tittleEditText.requestFocus();
			return false;
		} else if (contenteEditText.getText().length() == 0) {
			StringUtils.showToast(this, Config.ERROR_NO_SUBTITLE);
			contenteEditText.requestFocus();
			return false;
		} else if (contenteEditText.getText().length() < 10) {
			StringUtils.showToast(this, Config.ERROR_SUBTITLE_TOSHORT);
			contenteEditText.requestFocus();
			return false;
		}else if (imgs_path.size()==0) {
			StringUtils.showToast(this, Config.ERROR_NO_IMGS);
			ll_imgs.requestFocus();
			return false;
		}
		return true;
	}

	private void uploadGoods() {
		Tools();
		// 加载动画
		RequestParams params = new RequestParams();
		params.addBodyParameter("t_title", t_tittle);
		params.addBodyParameter("t_content", t_content);
		params.addBodyParameter("date", date);
		params.addBodyParameter("dongtaifenlei", dongtaifenlei + 1 + "");
		params.addBodyParameter("userid",PreferenceUtil.getInstance(getBaseContext()).getShareUserId());
		params.addBodyParameter("tieziid", tieziId);
		System.out.println(t_tittle + "--------" + t_content);
		System.out.println(date + "--------" + dongtaifenlei);
		System.out.println(tieziId + "--------" + t_content);
		// 获取图片的总数i 放到文件内，一并传到web端
		for (int i = 0; i < imgs_path.size(); i++) {
			params.addBodyParameter("" + i, new File(imgs_path.get(i)));
		}

		String uploadHost = JaderApplication.getIP() + "/Jader/InsertServlet";
		 JaderApplication.httpclient.configSoTimeout(5000);
		JaderApplication.httpclient.send(HttpMethod.POST, uploadHost, params,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						dialog2.show();
					}

					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						// 上传中
						dialog2.show();
						System.out.println("上传中  ");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// 上传成功，这里面的返回值，就是服务器返回的数据
						// String result = responseInfo.result;// 获取返回值
						System.out.println("上传成功");
						StringUtils.showToast(FActivity.this, "发布成功！");
						System.out.println(responseInfo.result);
						dialog2.dismiss();
						Intent intent1 = new Intent(FActivity.this, MainActivity.class);
						intent1.putExtra("tiaozhuan", 2);
						startActivity(intent1);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// 上传失败
						dialog2.dismiss();
						StringUtils.showToast(FActivity.this, "上传失败，请检查网络！");
						System.out.println("上传失败  ");

						Intent intent1 = new Intent(FActivity.this, MainActivity.class);
						intent1.putExtra("tiaozhuan", 2);
						startActivity(intent1);
					}
				});
	}
}
